﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace ConsoleApplication
{
    public static class DataTableExtensions
    {
        public static List<T> ToGenericList<T>(this DataTable dt) where T : new()
        {
            return (from row in dt.AsEnumerable()
                    select Convert<T>(row)).ToList();
        }

        private static T Convert<T>(DataRow row) where T : new()
        {
            var result = new T();
            var type = result.GetType();

            foreach (var property in type.GetProperties())
            {
                var dataRowKeyAttribute = property.GetCustomAttributes(typeof(DataRowKeyAttribute), true).FirstOrDefault() as DataRowKeyAttribute;
                if (dataRowKeyAttribute != null)
                {
                    property.SetValue(result, row[dataRowKeyAttribute.Key], null);
                }
            }

            return result;
        }
    }

    public class DataRowKeyAttribute : Attribute
    {
        public string Key
        {
            get;
            private set;
        }

        public DataRowKeyAttribute(string key)
        {
            Key = key;
        }
    }
}
